﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    class ForEachParser : ILineParser
    {
        private static readonly Regex ForEachPattern =
            new Regex(
                @"^For Each (?<var>[a-zA-Z][\w\$]*) In (?<collection>.+)$",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            var match = ForEachPattern.Match(lineContent);
            success = match.Success;
            if (!success) return lineContent;
            if (lineClosed || statuses.Peek().CurrentState == State.ClassDef)
            {
                throw new Exception();
            }
            lineClosed = true;
            statuses.Push(new ParseStatus {CurrentState = State.ForDef, StateInfo = match.Groups["var"].Value});
            
            return string.Format("foreach (var {0} in {1}){{", match.Groups["var"].Value,
                                 match.Groups["collection"].Value);
        }
    }
}
